﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace YF_Music.Core.Controls
{
  /// <summary>
  /// UnderlineRadioGroup.xaml 的交互逻辑 
  /// </summary>
  /// <remarks>
  /// <para><see cref="UnderlinePadding"/> — 设置底下亮条的边距。</para>
  /// <para><see cref="Padding"/> — 设置多个项之间的间距。</para>
  /// <para><see cref="ItemCommand"/> — 绑定命令 ICommand&lt;int?&gt;</para>
  /// <para><see cref="FontSize"/> — 设置项的文字大小。</para>
  /// <para><see cref="ItemsSource"/> — 设置项名</para>
  /// <para><see cref="SelectedIndex"/> — 设置选中的项</para>
  /// </remarks>
  public partial class UnderlineRadioGroup : UserControl
  {
    public UnderlineRadioGroup()
    {
      InitializeComponent();
      this.Loaded += UnderlineRadioGroup_Loaded;
    }

    public ICommand ItemCommand
    {
      get => (ICommand)GetValue(ItemCommandProperty);
      set => SetValue(ItemCommandProperty, value);
    }
    public static readonly DependencyProperty ItemCommandProperty =
    DependencyProperty.Register(nameof(ItemCommand), typeof(ICommand), typeof(UnderlineRadioGroup), new PropertyMetadata(null));


    private void UnderlineRadioGroup_Loaded(object sender, RoutedEventArgs e)
    {
      UpdateUnderlinePosition();
    }

    public static readonly DependencyProperty ItemsSourceProperty =
        DependencyProperty.Register(nameof(ItemsSource), typeof(IEnumerable), typeof(UnderlineRadioGroup), new PropertyMetadata(null));

    public IEnumerable ItemsSource
    {
      get => (IEnumerable)GetValue(ItemsSourceProperty);
      set => SetValue(ItemsSourceProperty, value);
    }

    public static readonly DependencyProperty SelectedIndexProperty =
        DependencyProperty.Register(nameof(SelectedIndex), typeof(int), typeof(UnderlineRadioGroup), new PropertyMetadata(0, OnSelectedIndexChanged));

    public int SelectedIndex
    {
      get => (int)GetValue(SelectedIndexProperty);
      set => SetValue(SelectedIndexProperty, value);
    }

    private static void OnSelectedIndexChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
      if (d is UnderlineRadioGroup group)
      {
        group.UpdateUnderlinePosition();
      }
    }

    private void RadioButton_Checked(object sender, RoutedEventArgs e)
    {
      if (sender is RadioButton rb)
      {
        var parent = VisualTreeHelper.GetParent(rb);
        int index = -1;

        var itemsControl = RootGrid.Children.OfType<ItemsControl>().FirstOrDefault();
        var items = itemsControl?.ItemsSource?.Cast<object>()?.ToList();
        if (items != null)
        {
          index = items.IndexOf(rb.DataContext);
        }

        if (index >= 0)
        {
          SelectedIndex = index;

          // 执行绑定的命令（传 index 作为参数）
          if (ItemCommand?.CanExecute(index) == true)
            ItemCommand.Execute(index);
        }
        UpdateUnderlinePosition(rb);
      }
    }


    private void UpdateUnderlinePosition(RadioButton target = null)
    {
      if (target == null)
      {
        var container = ItemsHost.ItemContainerGenerator.ContainerFromIndex(SelectedIndex) as FrameworkElement;
        if (container != null)
          target = FindChild<RadioButton>(container);
      }

      if (target == null) return;

      // 计算 target 相对于 RootGrid 的坐标
      var transform = target.TransformToAncestor(RootGrid);
      var position = transform.Transform(new Point(0, 0));

      DoubleAnimation moveAnim = new DoubleAnimation
      {
        To = position.X + UnderlinePadding,
        Duration = TimeSpan.FromMilliseconds(250),
        EasingFunction = new CubicEase { EasingMode = EasingMode.EaseInOut }
      };
      UnderlineTransform.BeginAnimation(TranslateTransform.XProperty, moveAnim);

      DoubleAnimation widthAnim = new DoubleAnimation
      {
        To = target.ActualWidth - 2 * UnderlinePadding,
        Duration = TimeSpan.FromMilliseconds(250),
        EasingFunction = new CubicEase { EasingMode = EasingMode.EaseInOut }
      };
      Underline.BeginAnimation(WidthProperty, widthAnim);
    }


    private T FindChild<T>(DependencyObject parent) where T : DependencyObject
    {
      int count = VisualTreeHelper.GetChildrenCount(parent);
      for (int i = 0; i < count; i++)
      {
        var child = VisualTreeHelper.GetChild(parent, i);
        if (child is T tChild)
          return tChild;
        var result = FindChild<T>(child);
        if (result != null)
          return result;
      }
      return null;
    }

    public double UnderlinePadding
    {
      get => (double)GetValue(UnderlinePaddingProperty);
      set => SetValue(UnderlinePaddingProperty, value);
    }
    public static readonly DependencyProperty UnderlinePaddingProperty =
        DependencyProperty.Register(nameof(UnderlinePadding), typeof(double), typeof(UnderlineRadioGroup), new PropertyMetadata(10d));

  }
}
